<template>
  <h4>购物车测试 (组合式API, 模块化store)</h4>

  <span>商品名:</span>
  <input placeholder="请输入商品名" v-model="goodsName">
  <span>单价:</span>
  <input type="number" placeholder="请输入单价" v-model="goodsPrice">
  <span>数量:</span>
  <input type="number" placeholder="请输入购买数量" v-model="buyQty">
  <button @click="doAddToCart">加入购物车</button>
  <br>
  <button @click="selectAllGoods(true)">选中全部商品</button>
  <button @click="selectAllGoods(false)">全部不选</button>

  <div>购物车已有商品: {{cartGoodsList}}</div>
  <p>
    件数:{{cartGoodsCount}}, 选中商品总金额: {{selGoodsAmount}}, 选中数量: {{selGoodsCount}}, <br>
    选中了全部商品? {{allGoodsSelected}}, 已经选中的第一个商品: {{hasGoodsSelected}}
  </p>
</template>

<script>
import {computed, ref} from 'vue'
import {useStore} from 'vuex'

export default {

  setup() {
    let goodsName = ref('')
    let goodsPrice = ref(0)
    let buyQty = ref(1)

    const store = useStore()
    const addToCart = (oneGoods)=> store.dispatch('addToCart', oneGoods)
    const selectAllGoods = (selected)=> store.commit('selectAllGoods', selected)

    function doAddToCart(){
      let oneGoods = {}
      oneGoods.id = goodsName.value  //just test: use name as id
      oneGoods.name = goodsName.value
      oneGoods.price = goodsPrice.value
      oneGoods.buyQty = buyQty.value
      addToCart(oneGoods).then(res => {
        console.log(res)
      })
    }

    return {
      goodsName, goodsPrice, buyQty,
      cartGoodsList: computed(()=> store.getters.cartGoodsList),
      cartGoodsCount: computed(()=> store.getters.cartGoodsCount),
      selGoodsAmount: computed(()=> store.getters.selGoodsAmount),
      selGoodsCount: computed(()=> store.getters.selGoodsCount),
      allGoodsSelected: computed(()=> store.getters.allGoodsSelected),
      hasGoodsSelected: computed(()=> store.getters.hasGoodsSelected),
      doAddToCart,
      selectAllGoods
    }
  },
}
</script>